package com.haixiaoke.flat.bill.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.auth.AuthCheck;
import com.haixiaoke.saas.bill.domain.ProprietorBill;
import com.haixiaoke.saas.bill.service.IProprietorBillService;
import com.haixiaoke.saas.common.config.WeChatConfig;
import com.haixiaoke.saas.common.constant.BillConstants;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.core.page.TableDataInfo;
import com.haixiaoke.saas.common.core.redis.RedisCache;
import com.haixiaoke.saas.common.enums.BillStateEnum;
import com.haixiaoke.saas.common.weChat.domain.UnifiedOrder;
import com.haixiaoke.saas.common.weChat.service.WeChatService;
import com.haixiaoke.saas.department.domain.WechatAccount;
import com.haixiaoke.saas.department.service.IWechatAccountService;
import com.haixiaoke.saas.system.BaseController;
import com.haixiaoke.saas.user.domain.UserConsumer;
import com.haixiaoke.saas.user.service.IUserConsumerService;
import com.haixiaoke.token.FrontTokenComponent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 业主账单Controller
 *
 * @author qixi
 * @date 2024-05-28
 */
@RestController
@RequestMapping("/front/flat/bill/proprietor")
public class FlatProprietorBillController extends BaseController {
    @Autowired
    private IProprietorBillService proprietorBillService;
    @Autowired
    private FrontTokenComponent frontTokenComponent;

    @Autowired
    private WeChatService weChatService;
    @Autowired
    private IWechatAccountService wechatAccountService;
    @Autowired
    private WeChatConfig weChatConfig;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IUserConsumerService userConsumerService;


    /**
     * 查询业主账单列表
     */
    @AuthCheck
    @GetMapping("/list")
    public TableDataInfo list(ProprietorBill proprietorBill) {
        startPage();
        proprietorBill.setUserId(frontTokenComponent.getUserId());
        List<ProprietorBill> list = proprietorBillService.selectProprietorBillList(proprietorBill);
        return getDataTable(list);
    }


    /**
     * 获取业主账单详细信息
     */
    @AuthCheck
    @GetMapping(value = "/{proprietorBillId}")
    public AjaxResult getInfo(@PathVariable("proprietorBillId") String proprietorBillId) {
        return success(proprietorBillService.selectProprietorBillByProprietorBillId(proprietorBillId));
    }


    /**
     * 业主账单支付
     */
    @AuthCheck
    @GetMapping(value = "/pay/{proprietorBillId}/{payType}")
    public AjaxResult pay(@PathVariable("proprietorBillId") String proprietorBillId, @PathVariable("payType") String payType) {

        ProprietorBill proprietorBill = proprietorBillService.selectProprietorBillByProprietorBillId(proprietorBillId);
        if (proprietorBill == null) {
            return AjaxResult.error("账单不存在");
        }

        if (BillStateEnum.BILL_STATE_PAID.getValue().equals(proprietorBill.getPayState())
                || BillStateEnum.BILL_STATE_LOGOUT.getValue().equals(proprietorBill.getPayState())) {
            return error("账单状态异常，请刷新后再试");
        }
        //
        // Object cacheObject = redisCache.getCacheObject(BillConstants.REDIS_PROPRIETOR_BILL_KEY + proprietorBillId);
        // if (cacheObject != null) {
        //     return error("请勿重复支付");
        // }

        UserConsumer userConsumer = userConsumerService.selectUserConsumerByUserId(frontTokenComponent.getUserIdNotNull());
        if (ObjectUtil.isEmpty(userConsumer) || StrUtil.isBlank(userConsumer.getOpenId())) {
            return error("用户数据异常");
        }
        String openId = userConsumer.getOpenId();
        WechatAccount account = wechatAccountService.selectWechatAccountByTenantId(proprietorBill.getTenantId());
        if (ObjectUtil.isEmpty(account)) {
            return error("商家信息错误，请联系管理员");
        }

        UnifiedOrder unifiedOrder = getUnifiedOrder(openId, account, proprietorBill);

        // 选择支付方式
        if (BillConstants.HOUSE_BILL_PAYMENT_TYPE_WECHAT.equals(payType)){
            redisCache.setCacheObject(BillConstants.REDIS_PROPRIETOR_BILL_KEY + proprietorBill.getProprietorBillId(), proprietorBill, 15, TimeUnit.MINUTES);
            return weChatService.unifiedOrder(unifiedOrder);
        }else {
            String url = redisCache.getCacheObject(BillConstants.REDIS_PROPRIETOR_BILL_NATIVE_PAY_REDIS_KEY + proprietorBillId);
            if (StrUtil.isBlank(url)){
                AjaxResult ajaxResult = weChatService.nativeOrder(unifiedOrder);
                url = StrUtil.toString(ajaxResult.get("data"));
                redisCache.setCacheObject(BillConstants.REDIS_PROPRIETOR_BILL_NATIVE_PAY_REDIS_KEY + proprietorBillId, url, 120, TimeUnit.MINUTES);
            }
            return AjaxResult.success("success", url);
        }

    }

    private UnifiedOrder getUnifiedOrder(String openId, WechatAccount account, ProprietorBill proprietorBill) {
        UnifiedOrder unifiedOrder = new UnifiedOrder();
        unifiedOrder.setAppId(weChatConfig.getAppId());
        unifiedOrder.setOpenId(openId);
        unifiedOrder.setAccountId(account.getAccountId());
        unifiedOrder.setAccountApiKey(account.getAccountApiKey());
        unifiedOrder.setAttach(account.getTenantId());
        unifiedOrder.setOutTradeNo(proprietorBill.getProprietorBillId()+"_"+ RandomUtil.randomNumbers(2));
        BigDecimal totalFee = proprietorBill.getCost();
        unifiedOrder.setCallBackUrl(weChatConfig.getProprietorBillPayCallBackUrl());
        unifiedOrder.setBody("房屋管家-业主账单支付");
        // TODO: 2024-6-5 金额写死
        unifiedOrder.setTotalFee(/*totalFee.multiply(BigDecimal.valueOf(100)).intValue()*/1);
        return unifiedOrder;
    }
}
